package com.sky.Task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时的待支付订单
     */
    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void ProcessOverTime(){
        log.info("要处理超时的待支付订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list=orderMapper.getByStatusAndOrderTimeLt(Orders.PENDING_PAYMENT,time);

        if(list!= null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason(MessageConstant.ORDER_OVER_TIME);
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 每天一点处理还在派送的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void ProcessSend(){
        log.info("处理用户收到餐但还是处于配送中的订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list= orderMapper.getByStatusAndOrderTimeLt(Orders.DELIVERY_IN_PROGRESS,time);
        if(list!=null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orderMapper.update(orders);
            }
        }
    }
}
